﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using TL_Cloud.API.Helpers;
using TL_Cloud.Common;
using TL_Cloud.Common.cache;
using TL_Cloud.RepositoryInterface.BookShop;
using TL_Cloud.ViewModels.BookShop;

namespace TL_Cloud.API.Controllers
{
    /// <summary>
    /// 用户授权控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : Controller
    {
        private readonly IBaseUserRepository _baseUserRepository;
        private readonly JwtSettings jwtSettings;
        private readonly ICache _cache;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtSetting"></param>
        /// <param name="baseUserReporsitory"></param>
        public AuthController(IOptions<JwtSettings> jwtSetting,
            IBaseUserRepository baseUserReporsitory,
            ICache cache
            )
        {
            this.jwtSettings = jwtSetting.Value;
            this._baseUserRepository = baseUserReporsitory;
            this._cache = cache;
        } 
        /// <summary>
        /// 生成用户的token
        /// </summary>
        /// <param name="logininfo"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Token([FromQuery]LoginViewModel logininfo)
        {
            if (ModelState.IsValid)
            {
                var userinfo = await _baseUserRepository.GetUserInfo(logininfo.userName, logininfo.password);
                if (userinfo != null)
                {
                    var claims = new Claim[] {
                        new Claim(ClaimTypes.Name,userinfo.UserName),
                        new Claim(ClaimTypes.NameIdentifier,userinfo.UserId),                  
                        new Claim(ClaimTypes.Role,userinfo.Role.ToString()),
                    };
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                    var token = new JwtSecurityToken(
                        jwtSettings.Issuer,
                        jwtSettings.Audience,
                        claims,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        creds
                        );
                    string tokenString = new JwtSecurityTokenHandler().WriteToken(token);
                  
                    return Ok(new
                    { 
                        token = "bearer " + tokenString,
                        userInfo = new
                        {
                            userid = userinfo.UserId,
                            username = userinfo.UserName,
                            headIcon = userinfo.HeadIcon,
                            role = userinfo.Role
                        }
                    });
                }
                else
                {
                    return BadRequest("登陆账号和密码不正确");
                }
            }
            else
            {
                return new MyUnprocessableEntityObjectResult(ModelState);
            }
        }
    }
}